package com.itboye.ihomebank.homefragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.service.LocationService;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.bean.HouseDetailBean;
import com.itboye.ihomebank.bean.HouseDetailBean.Neighbouring;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.constants.NetPublicConstant;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.custom.CarouselView;
import com.itboye.ihomebank.custom.RoundImageView;
import com.itboye.ihomebank.home.ActivityJinJiRenFangYuan;
import com.itboye.ihomebank.home.ActivityShenQingZuFang;
import com.itboye.ihomebank.home.ActivityYuYueKanfang;
import com.itboye.ihomebank.login.LoginActivity;
import com.itboye.ihomebank.presenter.HousePresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.XImageLoader;
import com.itboye.ihomebank.util.XPicasso;
import com.itboye.ihomebank.web.WebActivity;

/**
 * 房子详情
 * 
 */
public class HouseDetailActivity extends BaseOtherActivity implements Observer {

	LinearLayout house_contnainer;
	TextView lijiqianyue, yuyue, add_shap_title_tv;
	ImageView close_icon, img_setting, img_other;
	MapView mapView;
	private BaiduMap baiduMap;
	private LocationService locationService;
	private double lat, lng;
	private float radius;
	private MyLocationData locData;
	TextView collection;
	private HousePresenter housepresenter;
	private String status;
	private String favoriteId;
	private String fType;
	private String uid;
	private String houseNo;
	CarouselView img;
	private TextView house_name;
	private TextView house_tag;
	private TextView add;
	private TextView house_price;
	private TextView txt_huxing;
	private TextView txt_foor;
	private TextView txt_no;
	private HouseDetailBean bean;
	int isCollection = 0;
	private TextView txt_chuzuleixing;
	private TextView txt_tese;
	LinearLayout deviceContainer;
	private TextView txt_area;
	private TextView txt_chaoxiang;
	private AlertDialog alertDialog;
	public static int screenWidth;
	@Override
	protected int layout_id() {
		// TODO Auto-generated method stub
		SDKInitializer.initialize(getApplicationContext());
		return R.layout.activity_house_detail;
	}

	@Override
	protected void onInitController() {
		// TODO Auto-generated method stub

	}

	// 三个状态实现地图生命周期管理
	@Override
	protected void onDestroy() {
		// 退出时销毁定位
		// locationClient.stop();
		baiduMap.setMyLocationEnabled(false);
		// TODO Auto-generated method stub
		super.onDestroy();
		mapView.onDestroy();
		mapView = null;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		mapView.onResume();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		mapView.onPause();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		// initLocation();
	}

	@Override
	protected void onInit() {
		// TODO Auto-generated method stub
		// 注意该方法要再setContentView方法之前实现
		screenWidth=getWindowManager().getDefaultDisplay().getWidth();
		radius = getIntent().getFloatExtra("radius", 0);
		lat = getIntent().getDoubleExtra("lat", 0.000000);
		lng = getIntent().getDoubleExtra("lng", 0.000000);
		uid = getIntent().getStringExtra("uid");
		fType = "1";

		housepresenter = new HousePresenter(this);
		houseNo = getIntent().getStringExtra("house_no");
		favoriteId = houseNo;
		housepresenter.queryHouseDetail(houseNo, uid);
		baiduMap = mapView.getMap();
		initLocation();
		add_shap_title_tv.setText("找房");
		img_setting.setVisibility(View.VISIBLE);
		img_setting.setBackgroundResource(R.drawable.jingjiren2);
		img_other.setVisibility(View.VISIBLE);
		img_other.setBackgroundResource(R.drawable.share);

	}

	@Override
	protected void onReadIntent(Bundle bundle) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = null;
		switch (v.getId()) {
		case R.id.lijiqianyue:// 立即签约
			intent = new Intent(this, ActivityShenQingZuFang.class);
			intent.putExtra("house_no", bean.getHouseNo());
			startActivity(intent);
			break;
		case R.id.close_icon:
			finish();
			break;
		// case R.id.lijiqianyue:
		// break;
		case R.id.yuyue:// 预约看房
			intent = new Intent(this, ActivityYuYueKanfang.class);
			intent.putExtra("house_no", bean.getHouseNo());
			startActivity(intent);
			break;
		case R.id.collection:
			uid = SPUtils.get(this, null, SPContants.USER_ID, "") + "";
			if (uid == "") {
				intent = new Intent(this, LoginActivity.class);
				startActivity(intent);
			} else {
				housepresenter.collection(uid, fType, favoriteId,
						isCollection == 0 ? 1 : 0);
			}
			break;
		case R.id.img_setting:// 查看经纪人
			showJingJiRen();
			break;
		case R.id.img_other:// 分享
			break;
		case R.id.r:
			alertDialog.dismiss();
			intent = new Intent(this, ActivityJinJiRenFangYuan.class);
			intent.putExtra("model", bean);
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	void showJingJiRen() {
		 alertDialog = new AlertDialog.Builder(this).create();
		alertDialog.show();
		Window window = alertDialog.getWindow();
		window.setContentView(R.layout.alert_jingjiren);
		TextView tv_title = (TextView) window.findViewById(R.id.name);
		if (bean.getHouseType().equals("1")) {
			tv_title.setText("房东：" + bean.getOwnerInfo().getName());
		} else {
			tv_title.setText("经纪人：" + bean.getOwnerInfo().getName());
		}
		RoundImageView head = (RoundImageView) window.findViewById(R.id.head);
		XImageLoader.load(bean.getOwnerInfo().getHead(), head);
		RelativeLayout layout = (RelativeLayout) window.findViewById(R.id.r);
		layout.setOnClickListener(this);
	}

	private void initLocation() {
		// TODO Auto-generated method stub
		// -----------location config ------------
		System.out.println("lng" + lng + "lat" + lat);
		locData = new MyLocationData.Builder().accuracy(radius).direction(100)
				.latitude(lat).longitude(lng).build();
		// // 此处设置开发者获取到的方向信息，顺时针0-360
		baiduMap.setMyLocationData(locData); // 设置定位数据
		LatLng ll = new LatLng(lat, lng);
		MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(ll, 16); // 设置地图中心点以及缩放级别
		baiduMap.animateMapStatus(u);
		TextView textView = new TextView(MyApplcation.ctx);
		textView.setText("自定义的覆盖物");
		textView.setTextSize(16);
		// 将View转换为BitmapDescriptor
		BitmapDescriptor descriptor = BitmapDescriptorFactory
				.fromBitmap(BitmapFactory.decodeResource(getResources(),
						R.drawable.location));
		// 设置覆盖物属性，位置、标题、图标。。。
		MarkerOptions markerOptions = new MarkerOptions()
				.position(new LatLng(lat, lng)).icon(descriptor).title("标题")
				.zIndex(9).draggable(true);
		// 在地图上添加覆盖物
		mapView.getMap().addOverlay(markerOptions);

	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == HousePresenter.collection_success) {
				ByAlert.alert(entity.getData());
			} else if (entity.getEventType() == HousePresenter.collection_fail) {
				ByAlert.alert(entity.getData());
			} else if (entity.getEventType() == HousePresenter.houseDetail_success) {
				bean = (HouseDetailBean) entity.getData();
				isCollection = Integer.parseInt(bean.getIsFavorite());
				if (bean != null) {
					String imgIds = bean.getImgIds();
					if (imgIds != null) {
						String[] imgsArray = null;
						if (!imgIds.contains(",")) {
							imgsArray = new String[0];
							imgsArray[0] = imgIds;
						} else if (imgIds.contains(",")) {
							imgsArray = imgIds.split(",");
						}
						if (imgsArray != null) {
							ArrayList<ImageView> arrayBmps = new ArrayList<ImageView>();
							for (int i = 0; i < imgsArray.length; i++) {
								ImageView imageView = new ImageView(
										HouseDetailActivity.this);
								imageView.setScaleType(ScaleType.FIT_XY);
								XPicasso.loadImage(HouseDetailActivity.this,
										imageView, NetPublicConstant.IMAGE_URL
												+ imgsArray[i]);
								arrayBmps.add(imageView);
								imageView.setTag(i);
							}
							img.setImageBitmaps(arrayBmps);
							// //让顶部控件获取到焦点这样滚动条就自然停在顶部了
							img.setFocusable(true);
							img.setFocusableInTouchMode(true);
							img.requestFocus();
						}

						setHouseInfo(bean);
						setSheBei(bean);
						setNeighbouring(bean);
					}
				}
			} else if (entity.getEventType() == HousePresenter.houseDetail_fail) {
				ByAlert.alert(entity.getData());
			}
		}
	}

	private void setNeighbouring(HouseDetailBean bean) {
		// TODO Auto-generated method stub
		List<Neighbouring> listNeighbour = bean.getNeighbouring();

		for (int i = 0; i < listNeighbour.size(); i++) {
			View view = LayoutInflater.from(this).inflate(
					R.layout.item_tongxiaoqufangyuan, null);
			ImageView img_icon = (ImageView) view.findViewById(R.id.img_icon);
			TextView txt_addr = (TextView) view.findViewById(R.id.txt_addr);
			TextView money = (TextView) view.findViewById(R.id.money);
			XImageLoader.load(NetPublicConstant.IMAGE_URL
					+ listNeighbour.get(i).getMainImg(), img_icon);
			txt_addr.setText(listNeighbour.get(i).getArea() + "_"
					+ listNeighbour.get(i).getAreaZone() + "_"
					+ listNeighbour.get(i).getCommunity() + "_"
					+ listNeighbour.get(i).getAddressDetail());
			money.setText(Double.parseDouble(listNeighbour.get(i).getRent())/1000 + "元/月");
			android.widget.RelativeLayout.LayoutParams layoutParams = new android.widget.RelativeLayout.LayoutParams(
					screenWidth, android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT);
			
			android.widget.RelativeLayout.LayoutParams layoutParams02 = new android.widget.RelativeLayout.LayoutParams(
					screenWidth-60, (int) ((screenWidth-60)*0.75));
			layoutParams.setMargins(30, 10, 30, 10);
			layoutParams02.setMargins(30, 10, 30, 10);
			img_icon.setLayoutParams(layoutParams02);
//			layoutParams.
//			img_icon.setLayoutParams(layoutParams);
			house_contnainer.addView(view,layoutParams);
		}
	}

	private void setSheBei(HouseDetailBean bean) {
		// TODO Auto-generated method stub

	}

	private void setHouseInfo(HouseDetailBean bean) {
		// TODO Auto-generated method stub
		house_name.setText(bean.getTitle());
		house_tag.setText(bean.getTagNames());
		add.setText(bean.getAddressDetail());
		house_price.setText(bean.getRent() + "元/月");
		txt_no.setText(bean.getHouseNo());
		txt_foor.setText(bean.getFloorAt());
		txt_huxing.setText(bean.getHouseHall());
		txt_chuzuleixing.setText(bean.getRentType());
		txt_tese.setText(bean.getFacility());
		txt_area.setText(bean.getArea());
		txt_chaoxiang.setText(bean.getOrientation());
		if (bean.getFacility().contains(",")) {
			String[] devices = bean.getFacility().split(",");// 设备
			for (int i = 0; i < devices.length; i++) {
				View view = LayoutInflater.from(mContext).inflate(
						R.layout.item_other, null);
				android.widget.RelativeLayout.LayoutParams lP = new android.widget.RelativeLayout.LayoutParams(
						android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT,
						android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT);
				TextView textView = (TextView) view.findViewById(R.id.text);
				textView.setTextColor(mContext.getResources().getColor(
						R.color.black));
				lP.setMargins(0, 2, 2, 2);
				textView.setText(devices[i]);
				deviceContainer.addView(view);

			}
		} else {
			View view = LayoutInflater.from(mContext).inflate(
					R.layout.item_other, null);
			android.widget.RelativeLayout.LayoutParams lP = new android.widget.RelativeLayout.LayoutParams(
					android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT,
					android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT);
			TextView textView = (TextView) view.findViewById(R.id.text);
			textView.setTextColor(mContext.getResources().getColor(
					R.color.black));
			lP.setMargins(0, 2, 2, 2);
			textView.setText(bean.getFacility());
			deviceContainer.addView(view);
		}
	}
}
